package com.qsl.dbf;

import com.linuxense.javadbf.DBFException;
import com.linuxense.javadbf.DBFField;
import com.linuxense.javadbf.DBFReader;
import com.linuxense.javadbf.DBFRow;
import com.linuxense.javadbf.DBFUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;

public class JavaDBFReaderWithFieldNamesTest {


	public static void main(String args[]) {

		DBFReader readerOld = null, readerNew = null;
		try {

			// create a DBFReader object
			FileInputStream fis = new FileInputStream(
					new File("D:\\恒生聚源\\IDG 数据迁移\\第十三批迁移\\差异文件\\旧\\南方基金金手指估值\\PAR_STOCK20230206.dbf"));
			readerOld = new DBFReader(fis, Charset.forName("GBK"));

			FileInputStream fis2 = new FileInputStream(
					new File("D:\\恒生聚源\\IDG 数据迁移\\第十三批迁移\\差异文件\\新\\2655\\PAR_STOCK20230206.dbf"));
			readerNew = new DBFReader(fis2, Charset.forName("GBK"));

			// 比较列数量
			int numberOfFields = readerOld.getFieldCount();
			int newFields = readerNew.getFieldCount();
			if (numberOfFields != newFields) {
				System.out.println("字段数量不一致，旧IDG字段数：" + numberOfFields + "，新IDG字段数：" + newFields);
				return;
			}

			// 获取列名，并比较列名
			List<String> fieldNames = new ArrayList<>(numberOfFields);
			for (int i = 0; i < numberOfFields; i++) {
				DBFField field = readerOld.getField(i);
				DBFField fieldNew = readerNew.getField(i);
				if (!fieldNew.getName().equals(field.getName())) {
					System.out.println("列名不一致，第 " + (i+1) + " 列列名分别是，旧IDG是：" + field.getName()+ "，新IDG是：" + fieldNew.getName());
					return;
				}
				fieldNames.add(field.getName());
			}

			// 逐行比较每一列的内容
			DBFRow rowOld, rowNew;
			while ((rowOld = readerOld.nextRow()) != null && (rowNew = readerNew.nextRow()) != null) {
				for (int i=0; i<numberOfFields; i++) {
					String fieldName = fieldNames.get(i);
					String oldContent = rowOld.getString(fieldName);
					String newContent = rowNew.getString(fieldName);
					if (oldContent == null && newContent == null) {
						// 都为 null，认为一致
						continue;
					}
					if (!oldContent.equals(newContent)) {
						System.out.println("列：" + fieldName + " 的内容不相等，旧IDG的值为：" + oldContent + "，新IDG的值为：" + newContent);
						return;
					}
				}
			}

			System.out.println("内容一致");
		} catch (DBFException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		finally {
			DBFUtils.close(readerOld);
			DBFUtils.close(readerNew);
		}
	}
}
